/**
 * @Title: HomeActivity.java
 * @Copyright: XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * @Description: TODO<请描述此文件是做什么的>
 * @author: MeiYi
 * @data: 2015-11-30 上午9:36:10
 * @version: V1.0
 */

package artid.com.arttogo.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import artid.com.arttogo.R;
import artid.com.arttogo.app.ArtToGoApp;
import artid.com.arttogo.bean.NavigationItem;
import artid.com.arttogo.bean.PersonalCenter;
import artid.com.arttogo.bean.ShareItem;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.fragment.AttentionAndDynamicsActivity;
import artid.com.arttogo.fragment.HomeFragment;
import artid.com.arttogo.network.AppUrl;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.service.AudioService;
import artid.com.arttogo.service.BluetoothServiceOne;
import artid.com.arttogo.service.BluetoothServiceTwo;
import artid.com.arttogo.utils.MySharedPreferences;
import artid.com.arttogo.utils.ToastUtil;
import me.imid.swipebacklayout.lib.SwipeBackLayout;

import static artid.com.arttogo.R.id.imagedot_message;

/**
 * TODO<主界面>
 *
 * @author 熊彬
 * @data: 2015-11-30 上午9:36:10
 * @version: V1.0
 */
public class MainActivity extends BaseActivity implements
        OnCheckedChangeListener, OnClickListener {
    public static boolean MainActivityisExist = false;
    public static String UmToken = "";
    MySharedPreferences sharedPreferences;

    public Context context;
    int lastClick;
    private AttentionAndDynamicsActivity attentionDynamics;// 关注动态
    private HomeFragment home;// 主页面
    //    private SearchActivity search;// 列表式旧的搜索
    private MainQuery_Acivity search;// 瀑布流式新的搜索
    private PersonalActivity personalCenter;// 个人中心

    private RadioGroup radioGroup;// 底部导航菜单
    private Fragment mContent;// 当前页面

    private ImageView ivPlus, imageDot;
    /**
     * 用于对Fragment进行管理
     */
    private FragmentManager fragmentManager;
    private FragmentTransaction begin;
    public static String curFragmentTag;
    private int state = 0;// 当前页面状态
    String musicInt = "0";
    public static AudioService audioService;
    public static Boolean setMusicStop = false;

    public static Map<String, String> PushMessage = null;// 友盟推送信息
    // 环信头像
    public static String friendAvatar = null;// 头像
    public static Boolean isShowMessageDialog = null;// 是否显示消息对话框
    private List<EMConversation> conversationList;//环信消息数组
    private int unreadMesageNum=0;//环信未读条数
    private SwipeBackLayout mSwipeBackLayout;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if(conversationList!=null) {
                        conversationList.clear();
                        conversationList.addAll(loadConversationsWithRecentChat());
                        for (int i = 0; i < conversationList.size(); i++) {
                            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationList.get(i).conversationId());
                            unreadMesageNum = conversation.getUnreadMsgCount() + unreadMesageNum;
                        }
                        if (unreadMesageNum != 0) {
                            imageDot.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
                case 2:
                    List<EMMessage> list = new ArrayList<EMMessage>();
                    list = (List<EMMessage>) msg.obj;
                    try {
                        ArtToGoApp.showMessageDialog(MainActivity.this,
                                list.get(list.size() - 1));
                    } catch (Exception e) {
                        Log.d("log", "消息对话框显示错误：" + e);
                    }
                    break;
                default:
                    break;
            }
        }
    };
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    /*
     * (non-Javadoc)
     *
     * @see com.sigmatrix.artworkart.BaseActivity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.fragment_main);
        mSwipeBackLayout = getSwipeBackLayout();
        //设置是否可以滑动关闭
        mSwipeBackLayout.setEnableGesture(false);
        sharedPreferences = MySharedPreferences
                .getMySharedPreferences(MainActivity.this);
//        UmToken = UmengRegistrar.getRegistrationId(mContext);
//        Log.d("log", "友盟Token：" + UmToken);
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        AppUtil.deviceWidth = String.valueOf(width);
        ArtToGoApp.getInstance().addActivity(MainActivity.this);
        // AppUtil.regTowx(MainActivity.this);
//        QbSdk.preInit(this, new QbSdk.PreInitCallback() {
//
//            @Override
//            public void onViewInitFinished() {
//                // TODO Auto-generated method stub
//
//            }
//
//            @Override
//            public void onCoreInitFinished() {
//                // TODO Auto-generated method stub
//
//            }
//        });
        InitView();
//        setIbecan();
        initFragmentManger();
        reqDotData();


        // testPush();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    // void testPush(){
    // Intent collecterIntent = new
    // Intent(mContext,MallDetailPagerActivity.class);
    // String dataStr = getString(R.string.push_data_onsale);
    // dataStr = dataStr.replace("##", "382");
    // collecterIntent.putExtra("id", dataStr);
    // collecterIntent.putExtra("index", 0);
    // startActivity(collecterIntent);
    // }

    /**
     *
     */
    private void InitView() {
        // //透明状态栏
        // getWindow()
        // .addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        // 注册当前广播

        MainActivityisExist = true;
        IntentFilter filter = new IntentFilter("com.MainActivity.receiver");
        registerReceiver(broadcastReceiver, filter);

        radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
        fragmentManager = getSupportFragmentManager();
        radioGroup.setOnCheckedChangeListener(this);
        //单独设置查询图片大小
       /* RadioButton mRadioButton= (RadioButton) findViewById(R.id.radio_s);
        Resources res = mRadioButton.getResources();
        Drawable myImage = res.getDrawable(R.drawable.home_tab_search);
        myImage.setBounds(1, 1, 160, 160);//(x,y,width,height)
        mRadioButton.setCompoundDrawables(null, myImage, null, null);*/

        ivPlus = (ImageView) findViewById(R.id.radio_plus);
        ivPlus.setOnClickListener(this);
        imageDot = (ImageView) findViewById(R.id.main_imageDot);
        if (sharedPreferences.getValue(sharedPreferences.TagisPlayMusic, "0")
                .equals("1")) {
            musicInt = sharedPreferences.getValue(
                    sharedPreferences.TagMusicName, "0");
            Intent intent = new Intent();
            intent.setClass(this, AudioService.class);
            startService(intent);
            bindService(intent, conn, Context.BIND_AUTO_CREATE);
        }

        if (getIntent().getBooleanExtra("isHxNotification", false)) {
            EMMessage mEMMessage = getIntent().getParcelableExtra("message");
            // 用于环信通知栏点击之后的处理
            Intent intent = new Intent(mContext, ChatActivity.class);
            ChatActivity.message=mEMMessage;
            friendAvatar = mEMMessage.getStringAttribute("A_head", "http://172.16.0.3/upload/artPlatform/Addons/Avatar/default_128_128.png");
            isShowMessageDialog = getIntent().getBooleanExtra("isShowMessageDialog", false);
            startActivity(intent);
            mEMMessage = null;
        }

        if (isShowMessageDialog != null && isShowMessageDialog == true
                && ArtToGoApp.mEMMessage != null) {
            ArtToGoApp.showMessageDialog(MainActivity.this,
                    ArtToGoApp.mEMMessage);
        }

        if (PushMessage != null) {
            // 友盟推送点击通知栏处理
            String strType = PushMessage.get("messtype");
            VolleyBasic.printHashMap("uMengMEssage", PushMessage);
            try {
                if ("0".equals(strType)) {
                    // 系统消息
                    Intent i = new Intent(mContext, WebViewActivity.class);
                    i.putExtra("type", AppUrl.SYSTEMMESSAGE);
                    i.putExtra("url", PushMessage.get("messurl"));
                    i.putExtra("messageID", PushMessage.get("messid"));
                    Log.d("log", "推送消息ID：" + PushMessage.get("messid"));
                    startActivity(i);
                } else if ("2".equals(strType) || "3".equals(strType) || "7".equals(strType)) {
                    // 回复消息
                    Intent orderDetIntent = new Intent(mContext, OrderDetActivity.class);
                    orderDetIntent.putExtra("id",
                            PushMessage.get("art_id"));
                    startActivity(orderDetIntent);
                } else if ("8".equals(strType)) {
                    Intent collecterIntent = new Intent(mContext,
                            CollectionDetailPagerActivity.class);
                    collecterIntent.putExtra("id", PushMessage.get("art_id"));
                    collecterIntent.putExtra("titleName", PushMessage.get("consultationtitle"));
                    startActivity(collecterIntent);
                } else if ("6".equals(strType)) {
                    Intent intent = new Intent(mContext, WebViewActivity.class);
                    ShareItem si = new ShareItem();
                    si.setId(PushMessage.get("art_id"));
                    si.setImageUrl(PushMessage.get("consultationimg"));
                    si.setContent(PushMessage.get("consultationcontent"));
                    si.setTitle(PushMessage.get("consultationtitle"));
                    si.setUrl(PushMessage.get("messurl")
                            + PushMessage.get("art_id"));
                    intent.putExtra("share", si);
                    intent.putExtra("id", PushMessage.get("art_id"));
                    intent.putExtra("type", AppUrl.AUTH_NEWS);
                    startActivity(intent);
                } else if ("11".equals(strType)) {
                    //专场提醒
                    Intent intent = new Intent(mContext, AuctionSpecialInfo_Activity.class);
                    intent.putExtra("isPush", true);
                    intent.putExtra("SpecialID", PushMessage.get("art_id"));
                    intent.putExtra("messageID", PushMessage.get("messid"));
                    startActivity(intent);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
        getAdvBitmap(AdvActivity.savedUrl);
        // 环信登陆
        loginHX();
    }


    void getAdvBitmap(final String savedUrl) {
        Log.d("请求网络广告接口", "走了");
        VolleyBasic.getInstanceNoDialog((Activity) mContext).post(
                Cache.navigationList, VolleyMap.getInstance().navigationList(),
                NavigationItem.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(final VolleyData vd) {

                        // TODO Auto-generated method stub
                        NavigationItem item = (NavigationItem) vd.getData();
                        final String picUrl = item.getPath();
                        Log.d("请求网络广告接口", "网络图片地址：" + picUrl);
                        if (TextUtils.isEmpty(picUrl)) {
                            File f = AdvActivity.picFile;
                            if (f.exists()) {
                                f.delete();
                            }
                            sharedPreferences.setValue(AdvActivity.advTag, "");
                        }
                        // 比对
                        if (!savedUrl.equals(picUrl)) {

                            Glide.with(mContext).load(picUrl).asBitmap()
                                    .into(new SimpleTarget<Bitmap>() {

                                        @Override
                                        public void onResourceReady(
                                                Bitmap arg0,
                                                GlideAnimation<? super Bitmap> arg1) {
                                            // TODO Auto-generated method stub

                                            saveBitmap(arg0, vd.getJson());

                                            // loadAdv();
                                        }
                                    });
                        }
//						File f = AdvActivity.picFile;
//						f.delete();

                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        File f = AdvActivity.picFile;
                        if (f.exists()) {
                            f.delete();
                        }
                        sharedPreferences.setValue(AdvActivity.advTag, "");
                    }
                });

    }

    public void saveBitmap(Bitmap bm, String data) {
        File f = AdvActivity.picFile;
        Log.d("开始保存图片", "地址：" + f.getAbsolutePath());
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            sharedPreferences.setValue(AdvActivity.advTag, data);
            Log.d("广告页缓存", "已经保存" + f.getAbsolutePath());
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    void setIbecan() {
        String isOpen = sharedPreferences.getValue("isOpenBluetooth", "false");
        if (isOpen.equals("true")) {
            Intent serviceOne = new Intent();
            serviceOne.setClass(mContext, BluetoothServiceOne.class);
            startService(serviceOne);
            Intent serviceTwo = new Intent();
            serviceTwo.setClass(mContext, BluetoothServiceTwo.class);
            startService(serviceTwo);
        } else {
            Intent serviceOne = new Intent();
            serviceOne.setClass(mContext, BluetoothServiceOne.class);
            Intent serviceTwo = new Intent();
            serviceTwo.setClass(mContext, BluetoothServiceTwo.class);
            stopService(serviceOne);
            stopService(serviceTwo);
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter
                    .getDefaultAdapter();
            if (bluetoothAdapter != null) {
                bluetoothAdapter.disable();
            }

        }
    }

    /**
     * @Description: 初始化FragmentManger
     * @Title: initFragmentManger
     * @param:
     * @return: void
     * @author: JianBo Yang
     */
    private void initFragmentManger() {
        home = new HomeFragment();
        mContent = home;
        fragmentManager = getSupportFragmentManager();
        begin = fragmentManager.beginTransaction();
        begin.add(android.R.id.tabcontent, mContent);
        begin.commit();
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            audioService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            // 这里我们实例化audioService,通过binder来实现
            audioService = ((AudioService.AudioBinder) binder)
                    .getService(Integer.valueOf(musicInt));
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private long clickTime = 0; // 记录第一次点击的时间

    private void exit() {
        if ((System.currentTimeMillis() - clickTime) > 2000) {
            // Config.showTipNew(getApplicationContext(), "再按一次后退键退出程序",
            // ScreenWidth)

            Toast.makeText(getApplicationContext(), "再按一次后退键退出程序",
                    Toast.LENGTH_SHORT).show();
            clickTime = System.currentTimeMillis();
        } else {
            if (audioService != null) {
                audioService.pauseMusic();
            }
            audioService = null;
            this.finish();
            // System.exit(0);
        }
    }

    public void switchContent(Fragment from, Fragment to) {
        if (from != to) {
            mContent = to;
            FragmentTransaction transaction = fragmentManager
                    .beginTransaction();
            // 先判断是否被add过
            if (!to.isAdded()) {
                // 隐藏当前的fragment，add下一个到Activity中
                transaction.hide(from).add(android.R.id.tabcontent, to)
                        .commit();
            } else {
                // 隐藏当前的fragment，显示下一个
                transaction.hide(from).show(to).commit();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        reqDotData();
        //获取环信未读条数
        refreshHxMessage();
        switch (state) {
            case 0:
                switchContent(mContent, home);
                break;
            case 1:
                //关注页面
                if (attentionDynamics == null) {
                    attentionDynamics = new AttentionAndDynamicsActivity();
                }
                switchContent(mContent, attentionDynamics);
                break;
            case 2:
                //查询页面
                if (search == null) {
//                    search = new SearchActivity();//老版搜索
                    search = new MainQuery_Acivity();//新版瀑布流搜索
                }
                switchContent(mContent, search);
                break;
            case 3:
                //我的
                if (personalCenter == null) {
                    personalCenter = new PersonalActivity();
                }
                switchContent(mContent, personalCenter);
                break;

            default:
                break;
        }
        // MobclickAgent.onResume(this);
    }

    /*
     * (non-Javadoc)
     *
     * @see android.widget.RadioGroup.OnCheckedChangeListener#onCheckedChanged(
     * android .widget.RadioGroup, int)
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentManager fm = getSupportFragmentManager();

        switch (checkedId) {
            case R.id.radio_h:
                // setTabSelection(getString(R.string.main_mutualaid));
                lastClick = R.id.radio_h;
                switchContent(mContent, home);
                state = 0;
                break;
            case R.id.radio_ad:
                if (!AppUtil.LoginVer(MainActivity.this)) {
                    state = 1;
                    if (attentionDynamics == null) {
                        attentionDynamics = new AttentionAndDynamicsActivity();
                    }
                    switchContent(mContent, attentionDynamics);
                    lastClick = R.id.radio_ad;
                } else {
                    radioGroup.check(lastClick);
                }

                break;
            case R.id.radio_s:
                lastClick = R.id.radio_s;
                state = 2;
                if (search == null) {
//                    search = new SearchActivity();//老版搜索
                    search = new MainQuery_Acivity();//新版瀑布流搜索
                }
                switchContent(mContent, search);
                // setTabSelection(getString(R.string.main_news));
                break;

            case R.id.radio_pc:
                if (!AppUtil.LoginVer(MainActivity.this)) {
                    state = 3;
                    if (personalCenter == null) {
                        personalCenter = new PersonalActivity();
                    }
                    switchContent(mContent, personalCenter);
                    lastClick = R.id.radio_pc;
                } else {
                    radioGroup.check(lastClick);
                }

                break;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View view) {
//        // TODO Auto-generated method stub
        switch (view.getId()) {
//            case R.id.rel_plus:
//                if (shelter.getVisibility() == View.GONE) {
//                    openPlus();
//                } else if (shelter.getVisibility() == View.VISIBLE) {
//                    exitPlus();
//                }
//                break;
//            case R.id.rel_main_shelter:
//                exitPlus();
//                break;
//            case R.id.iv_main_pt:
//                startActivity(new Intent(this, TakePhoteActivity.class));
//                // selectFromCamera();
//
//                break;
            case R.id.radio_plus:
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivity(intent);
                break;
//            case R.id.rel_main_pz:
//                Intent intentPhoto = new Intent(MainActivity.this,
//                        PhotoIdentificationActivity.class);
//                startActivity(intentPhoto);
//                exitPlus();
//
//                break;
//
//            default:
//                break;
        }
    }

//    public void selectFromCamera() {
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//        startActivityForResult(intent, 1);
//    }
//
//    public void selectFromAlbum() {
//        Intent intent = new Intent(Intent.ACTION_PICK,
//                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        // 剪裁
//        // intent.setType("image/*");
//        //
//        // intent.putExtra("crop", "false");
//        //
//        // intent.putExtra("aspectX", 2);
//        //
//        // intent.putExtra("aspectY", 2);
//        //
//        // intent.putExtra("outputX", 600);
//        //
//        // intent.putExtra("outputY", 600);
//        //
//        // intent.putExtra("scale", true);
//        //
//        // intent.putExtra("return-data", false);
//        //
//        // intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//        //
//        // intent.putExtra("outputFormat",
//        // Bitmap.CompressFormat.JPEG.toString());
//        startActivityForResult(intent, 2);
//    }

//    @Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		// /**使用SSO授权必须添加如下代码 */
//
//		switch (requestCode) {
//		case 1:// 如果是直接从相册获取
//			if (data != null) {
//				// 取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，但是在拍照中有得机子呢Uri是空的，所以要特别注意
//				Uri mImageCaptureUri = data.getData();
//				// 返回的Uri不为空时，那么图片信息数据都会在Uri中获得。如果为空，那么我们就进行下面的方式获取
//				if (mImageCaptureUri != null) {
//					Bitmap image;
//					try {
//						// 这个方法是根据Uri获取Bitmap图片的静态方法
//						image = MediaStore.Images.Media.getBitmap(
//								this.getContentResolver(), mImageCaptureUri);
//						if (image != null) {
//							// imageView.setImageBitmap(image);
//						}
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				} else {
//					Bundle extras = data.getExtras();
//					if (extras != null) {
//						// 这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
//						Bitmap image = extras.getParcelable("data");
//						if (image != null) {
//							Intent intentShoot = new Intent(MainActivity.this,
//									ShootGraphQueryActivity.class);
//							startActivity(intentShoot);
//							// imageView.setImageBitmap(image);
//						}
//					}
//				}
//
//			}
//			break;
//
//		case 2:
//			Uri selectedImage = data.getData();
//			String[] filePathColumn = { MediaStore.Images.Media.DATA };
//			Cursor cursor = getContentResolver().query(selectedImage,
//					filePathColumn, null, null, null);
//			cursor.moveToFirst();
//			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//			String picturePath = cursor.getString(columnIndex);
//			cursor.close();
//			// imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
//			// 剪裁的话
//			// if (data == null) {
//			// return;
//			// }
//			// if (imageUri != null) {
//			// Bitmap bitmap = decodeUriAsBitmap(imageUri);// decode bitmap
//			// imageView.setImageBitmap(bitmap);
//			//
//			// }
//			break;
//		}
//		super.onActivityResult(requestCode, resultCode, data);
//
//	}

//    void setImage() {
//        String sdStatus = Environment.getExternalStorageState();
//        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
//            // Log.v("TestFile",
//            // "SD card is not avaiable/writeable right now.");
//            Toast.makeText(this, "储存不可用，请检查", 300).show();
//            return;
//        }
//        if (path != null) {
//            Bitmap bitmap = decodeUriAsBitmap(Uri.fromFile(new File(path)));// decode
//            // bitmap
//            ivPlus.setImageBitmap(bitmap);
//
//            // ivPlus.setImageResource(R.drawable.ic_normal);
//
//        }
//    }

    private Bitmap decodeUriAsBitmap(Uri uri) {

        Bitmap bitmap = null;
        try {

            bitmap = BitmapFactory.decodeStream(getContentResolver()
                    .openInputStream(uri));

        } catch (FileNotFoundException e) {

            e.printStackTrace();

            return null;

        }

        return bitmap;

    }

    /**
     * 友盟通知栏判断
     */
    private void UmengNotificationJudge(String messgaeURL, String MessageId) {
        if (!ArtToGoApp.isForeground(mContext,
                "com.aicpsp.artworkartc.WebViewActivity")) {
            // 判断要打开的页面否已经打开
            Intent i = new Intent(mContext, WebViewActivity.class);
            i.putExtra("type", AppUrl.LOAD_HOMEPAGE_WEB);
            i.putExtra("url", messgaeURL);
            i.putExtra("messageID", MessageId);
            startActivity(i);
        }
    }

    /**
     * 环信登陆
     */
    private void loginHX() {
        if (!TextUtils.isEmpty(AppUtil.getUser().getUid())) {
            EMClient.getInstance().login(AppUtil.getUser().getUid(),
                    "yjbgp2016", new EMCallBack() {// 回调
                        @Override
                        public void onSuccess() {
                            Activity activity = (Activity) mContext;
                            activity.runOnUiThread(new Runnable() {
                                public void run() {

                                    Log.d("log", "环信:登陆聊天服务器成功！");
                                }
                            });
                        }

                        @Override
                        public void onProgress(int progress, String status) {
                            Log.d("log", "环信:登陆中！");
                        }

                        @Override
                        public void onError(int code, String message) {
                            Log.d("log", "环信:登陆聊天服务器失败！");
                            loginHX();
                        }
                    });
        }
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

    /**
     * 刷新环信会话列表
     */
    public void refreshHxMessage() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                mHandler.sendEmptyMessage(1);
            }
        }).start();
    }

    /**
     * 环信消息接收
     */
    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onCmdMessageReceived(List<EMMessage> list_EMMessage) {
            // TODO Auto-generated method stub
            // 透传消息
            Log.d("log", "环信透传消息:" + list_EMMessage.toString());

        }

        @Override
        public void onMessageRead(List<EMMessage> list) {

        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {

        }

        @Override
        public void onMessageChanged(EMMessage arg0, Object arg1) {
            // TODO Auto-generated method stub
            // 消息状态变动
        }


        @Override
        public void onMessageReceived(final List<EMMessage> list_EMMessage) {
            // TODO Auto-generated method stub
            // 收到消息
            Log.d("log", "环信消息:" + list_EMMessage.toString());
            // 消息提示框
            Message msg = mHandler.obtainMessage(2, list_EMMessage);
            mHandler.sendMessage(msg);
        }
    };

    // 广播监听
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub


            if (intent.getBooleanExtra("PushOnClick", false) == true) {
                if ("0".equals(intent.getStringExtra("UmMessageType"))) {
                    // 系统消息
                    UmengNotificationJudge(
                            intent.getStringExtra("UmMessageMessurl"),
                            intent.getStringExtra("UmMessageID"));
                } else if ("1".equals(intent.getStringExtra("UmMessageType"))) {
                    // 回复消息
                    Intent intent2 = new Intent(MainActivity.this,
                            CollectionDetailPagerActivity.class);
                    intent2.putExtra("id", intent.getStringExtra("art_id"));
                    //这里缺少标题传递
                    intent2.putExtra("titleName", "详情");
                    startActivity(intent2);
                }
            }
            if (intent.getBooleanExtra("DotView", false)) {
                imageDot.setVisibility(View.VISIBLE);
            } else {
                imageDot.setVisibility(View.GONE);
            }

        }
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        // 清空推送
        MainActivityisExist = false;
        MainActivity.PushMessage = null;
        // 关闭广播
        unregisterReceiver(broadcastReceiver);
    }


    /**
     * 获取消息条数
     */
    void reqDotData() {
        // System.out.println("token=" + AppUtil.getUser().getToken());
        VolleyBasic.getInstanceNoDialog(MainActivity.this).post(
                Cache.personalCenter,
                VolleyMap.getInstance().personalCenter(
                        AppUtil.getUser().getToken()), PersonalCenter.class,

                new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        if (vd.getCode() == -99) {
                            imageDot.setVisibility(View.GONE);
                            return;
                        }
                        PersonalCenter pc = (PersonalCenter) vd.getData();
                        if (pc == null) {
                            return;
                        }
                        if (pc.getSystemread() == 1 || pc.getCommentread() == 1 || unreadMesageNum>0) {
                            imageDot.setVisibility(View.VISIBLE);
                        } else {
                            imageDot.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    /**
     * 用于给Fragment触摸事件接口
     */
    private ArrayList<MyOnTouchListener> onTouchListeners = new ArrayList<MyOnTouchListener>(
            10);

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (MyOnTouchListener listener : onTouchListeners) {
            listener.onTouch(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public void registerMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
        onTouchListeners.add(myOnTouchListener);
    }

    public void unregisterMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
        onTouchListeners.remove(myOnTouchListener);
    }

    public interface MyOnTouchListener {
        public boolean onTouch(MotionEvent ev);
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
    /**
     * 获取所有会话
     *
     * @return +
     */
    private List<EMConversation> loadConversationsWithRecentChat() {
        // 获取所有会话，包括陌生人
        Map<String, EMConversation> conversations = EMClient.getInstance()
                .chatManager().getAllConversations();
        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation
                            .getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        for (int i = 0; i < list.size(); i++) {
            Log.d("log", "环信会话列表：" + list.get(i).getLastMessage().toString());
        }

        return list;
    }

    /**
     * 根据最后一条消息的时间排序
     *
     */
    private void sortConversationByLastChatTime(
            List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList,
                new Comparator<Pair<Long, EMConversation>>() {
                    @Override
                    public int compare(final Pair<Long, EMConversation> con1,
                                       final Pair<Long, EMConversation> con2) {

                        if (con1.first == con2.first) {
                            return 0;
                        } else if (con2.first > con1.first) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }

                });
    }
}
